package gw.com.android.ui.quote2;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.GTConfig;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.view.EfficientRecyclerView;
import www.com.library.view.LoadingProgress;
import www.com.library.view.TintImageTextView;

/**
 * 行情自选涨幅列表界面
 */
public class QuoteSelfFragment2 extends PushMsgTabFragment {

    /**
     * 数据加载圈
     */
    @BindView(R.id.loading_progress_view)
    LoadingProgress mProgress;
    @BindView(R.id.percent_view)
    TextView mPrecentView;
    /**
     * 产品列表控件
     **/
    @BindView(R.id.lv_product_list)
    EfficientRecyclerView mListView;
    @BindView(R.id.empty_layout)
    LinearLayout mEmptyLayout;
    @BindView(R.id.empty_icon)
    TintImageTextView mEmptyIcon;
    @BindView(R.id.hot_click)
    TextView mHotView;

    @BindView(R.id.title_layout)
    LinearLayout mTitleLayout;

    QuoteProductListAdapter2 mAdapter;

    public QuoteSelfFragment2() {
    }

    public static QuoteSelfFragment2 newInstance() {
        QuoteSelfFragment2 fragment = new QuoteSelfFragment2();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mCurTypeId = getArguments().getString(QuoteInsideFragment.CODE_ID_TAG);
            mCurTypeName = getArguments().getString(QuoteInsideFragment.NAME_TAG);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_new_quote_self2;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        // 抢占点击事件，以便下层界面不可点击
        mProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        // 线性布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        // 设置布局管理器
        mListView.setLayoutManager(linearLayoutManager);
//        mListView.addItemDecoration(new RecycleViewDivider(
//                getActivity(), LinearLayoutManager.VERTICAL, R.drawable.common_divider_left20_bg, false));

        mEmptyIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.showQuoteSelfAddActivity(getActivity());
            }
        });
        mHotView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityManager.showQuoteSelfAddActivity(getActivity());
            }
        });
    }

    @Override
    protected void initViewData() {
        mAdapter = new QuoteProductListAdapter2(this, getActivity(), mCurTypeId);
        mListView.setAdapter(mAdapter);
        mListView.setVisibility(View.GONE);
        setFooterView(mListView);
        View foot = mAdapter.getFooterView();
        if (foot != null)
            foot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityManager.showQuoteSelfAddActivity(getActivity());
                    MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickSearch3");
                }
            });
        refreshViewData();
        setPrecentView();
    }

    @Override
    public void registerRxBus() {
        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {


                    }
                });

        bindSubscription(quoteAllRegister);

        Disposable positionListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_POSTION_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        Logger.i("持仓列表刷新MainActivity 持仓列表回包接收到回调");
                        refreshViewData();
                    }
                });
        bindSubscription(positionListRegister);

        Disposable quoteListRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteListRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        onSymbolNotify();
                    }
                });

        bindSubscription(quoteUpdateRegister);

        Disposable quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        if (null != model) {
                            onSymbolNotify(model.getInt(GTSConst.JSON_KEY_CODEID));
                        }
                    }
                });

        bindSubscription(quoteTickRegister);

        Disposable quoteSelfRegister = RxBus.getInstance().register(GTSConst.REPLY_QUOTE_SELF, DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {

                        int x = mCurTypeId.equals(GTSConst.ZONE_TYPE_SELF + "") ? 2 : 1;// 这里要判断Footer是否存在。因为footer会计算到item数目中
                        if (mAdapter.getItemCount() < x) {
                            mListView.setVisibility(View.GONE);
                            mTitleLayout.setVisibility(View.GONE);
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        } else {
                            mListView.setVisibility(View.VISIBLE);
                            mTitleLayout.setVisibility(View.VISIBLE);
                            mEmptyLayout.setVisibility(View.GONE);
                        }
                    }
                });

        bindSubscription(quoteSelfRegister);
    }

    /**
     * 为recyclerView添加footview
     */
    private void setFooterView(RecyclerView mRecyclerView) {
        View footer = LayoutInflater.from(getActivity()).inflate(R.layout.list_footview_quote_item, mRecyclerView, false);
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
            footer.findViewById(R.id.view_stub).setVisibility(View.VISIBLE);
        } else {
            footer.findViewById(R.id.view_stub).setVisibility(View.GONE);
        }
        if (null != mAdapter) {
            if (mCurTypeId.equals(GTSConst.ZONE_TYPE_SELF + "")) {
                mAdapter.setFooterView(footer);
            } else {
                mAdapter.setFooterView(null);
            }
        }
    }

    /**
     * 还原涨跌设置
     */
    private void setPrecentView() {
        if (GTConfig.instance().mSortType == AppContances.SORT_NORMAL_TYPE) {
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortstay, 0);
        } else if (GTConfig.instance().mSortType == AppContances.SORT_DOWN_TYPE) {
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortdown, 0);
        } else if (GTConfig.instance().mSortType == AppContances.SORT_UP_TYPE) {
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortup, 0);
        }
    }

    /**
     * 刷新行情界面数据
     */
    protected void refreshViewData() {
        Logger.e("QuoteSelfFragment refreshViewData " + mCurTypeId + (null == mAdapter) + (null == mEmptyLayout) + (null == mListView));
        if (null == mAdapter || null == mEmptyLayout || null == mListView) {
            return;
        }
        if (!mListView.mIsOnTouch && !mListView.mIsScrolling) {
            mAdapter.refreshSortData(GTConfig.instance().mSortType);
        }
        Logger.e("QuoteSelfFragment isLoading " + DataManager.instance().getLoadDataState(mCurTypeId + ""));
        if (DataManager.instance().getLoadDataState(mCurTypeId + "")) {
            int x = mCurTypeId.equals(GTSConst.ZONE_TYPE_SELF + "") ? 2 : 1;// 这里要判断Footer是否存在。因为footer会计算到item数目中
            if (mAdapter.getItemCount() < x) {
                mListView.setVisibility(View.GONE);
                mTitleLayout.setVisibility(View.GONE);
                if (mCurTypeId.equals(GTSConst.ZONE_TYPE_SELF + ""))//只有 自选这一栏，才显示这个+号
                    mEmptyLayout.setVisibility(View.VISIBLE);
            } else {
                mListView.setVisibility(View.VISIBLE);
                mTitleLayout.setVisibility(View.VISIBLE);
                mEmptyLayout.setVisibility(View.GONE);
            }
        } else {
            mListView.setVisibility(View.GONE);
            mTitleLayout.setVisibility(View.GONE);
            mEmptyLayout.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.percent_view)
    void onPercentClick() {
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        if (null == mAdapter || mAdapter.getItemCount() < 2) {
            return;
        }
        if (GTConfig.instance().mSortType == AppContances.SORT_NORMAL_TYPE) {
            GTConfig.instance().mSortType = AppContances.SORT_DOWN_TYPE;
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortdown, 0);
            mPrecentView.setTextColor(getResources().getColor(R.color.color_w));
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickChangeSort2");
            PackStatis.getToService(PackStatis.EventAction.CLICKCHANGESORT.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, "2");
        } else if (GTConfig.instance().mSortType == AppContances.SORT_DOWN_TYPE) {
            GTConfig.instance().mSortType = AppContances.SORT_UP_TYPE;
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortup, 0);
            mPrecentView.setTextColor(getResources().getColor(R.color.color_w));
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickChangeSort1");
            PackStatis.getToService(PackStatis.EventAction.CLICKCHANGESORT.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, "1");
        } else if (GTConfig.instance().mSortType == AppContances.SORT_UP_TYPE) {
            GTConfig.instance().mSortType = AppContances.SORT_NORMAL_TYPE;
            mPrecentView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.a_quote_sortstay, 0);
            mPrecentView.setTextColor(Color.parseColor("#9a9a9a"));
            MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "ClickChangeSort3");
            PackStatis.getToService(PackStatis.EventAction.CLICKCHANGESORT.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, "3");
        }
        Logger.e("排序类型点击 == " + GTConfig.instance().mSortType);
        if (null != mAdapter) {
            mAdapter.refreshSortData(GTConfig.instance().mSortType);
        }
        MobclickEventUtlis.MobclickEventByAccountType(getActivity(), "Range_up");
    }

    @Override
    public void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCodes(mCurTypeId));
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isVisible()) {
            refreshViewData();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            startCountDownTimer();
            refreshViewData();
        }
    }

    @Override
    public void onSymbolNotify() {
        super.onSymbolNotify();
//        Logger.i("QuoteItem onSymbolNotify 收到行情列表回调操作 " + mZoneType);
        refreshViewData();
    }

    @Override
    public void onSymbolNotify(int codeId) {
        super.onSymbolNotify(codeId);
        if (null != mListView && !mListView.mIsOnTouch && !mListView.mIsScrolling) {//listView不为空，并且不处于被操作的状态
            if (null != mAdapter && mCurTypeName != null && mCurTypeName.equals(NewQuoteFragment.mTypeName)) {//并且adapter不为空，还要保证 用户选择的产品，和当前这个fragment显示的产品类别相同，才去刷新
                mAdapter.refreshData(codeId);
            }
        }
    }
}
